{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Scale-Free Networks\n",
    "\n",
    "Code examples from [Think Complexity, 2nd edition](http://greenteapress.com/wp/complexity2), Chapter 4\n",
    "\n",
    "Copyright 2016 Allen Downey, [MIT License](http://opensource.org/licenses/MIT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function, division\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import networkx as nx\n",
    "import numpy as np\n",
    "import random\n",
    "\n",
    "import thinkplot\n",
    "\n",
    "# colors from our friends at http://colorbrewer2.org\n",
    "COLORS = ['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462',\n",
    "          '#b3de69','#fccde5','#d9d9d9','#bc80bd','#ccebc5','#ffed6f']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from thinkstats2 import RandomSeed\n",
    "RandomSeed(17)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Facebook data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following function reads a file with one edge per line, specified by two integer node IDs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_graph(filename):\n",
    "    G = nx.Graph()\n",
    "    array = np.loadtxt(filename, dtype=int)\n",
    "    G.add_edges_from(array)\n",
    "    return G"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll read the Facecook data downloaded from [SNAP](https://snap.stanford.edu/data/egonets-Facebook.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://snap.stanford.edu/data/facebook_combined.txt.gz\n",
    "\n",
    "fb = read_graph('facebook_combined.txt.gz')\n",
    "n = len(fb)\n",
    "m = len(fb.edges())\n",
    "n, m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With larger graphs, it takes too long to compute clustering coefficients and path lengths, but we can estimate them by sampling.  NetworkX provides a function in its approximation module that estimates the clustering coefficient:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from networkx.algorithms.approximation import average_clustering"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And I've written a function that estimates the average path length."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def random_path_lengths(G, nodes=None, trials=1000):\n",
    "    \"\"\"Choose random pairs of nodes and compute the path length between them.\n",
    "\n",
    "    G: Graph\n",
    "    nodes: list of nodes to choose from\n",
    "    trials: number of pairs to choose\n",
    "\n",
    "    returns: list of path lengths\n",
    "    \"\"\"\n",
    "    if nodes is None:\n",
    "        nodes = list(G)\n",
    "    else:\n",
    "        nodes = list(nodes)\n",
    "        \n",
    "    pairs = np.random.choice(nodes, (trials, 2))\n",
    "    lengths = [nx.shortest_path_length(G, *pair) \n",
    "               for pair in pairs]\n",
    "    return lengths\n",
    "\n",
    "def estimate_path_length(G, nodes=None, trials=1000):\n",
    "    return np.mean(random_path_lengths(G, nodes, trials))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The average clustering coefficient is high."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "C = average_clustering(fb)\n",
    "C"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The average path length is low."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L = estimate_path_length(fb)\n",
    "L"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## WS Graph"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next I'll construct a WS graph with the same number of nodes and average degree as the Facebook network:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = len(fb)\n",
    "m = len(fb.edges())\n",
    "k = int(round(2*m/n))\n",
    "k"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `p=0` we get a ring lattice.\n",
    "\n",
    "The number of edges is a little bigger than in the dataset because we have to round `k` to an integer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lattice = nx.watts_strogatz_graph(n, k, p=0)\n",
    "len(lattice), len(lattice.edges())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The clustering coefficient is a little higher than in the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "C, average_clustering(lattice)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the path length is much higher."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L, estimate_path_length(lattice)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `p=1` we get a random graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "random_graph = nx.watts_strogatz_graph(n, k, p=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The clustering coefficient is small."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "C, average_clustering(random_graph)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the path lengths are very small."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L, estimate_path_length(random_graph)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By trial and error, I found that `p=0.05` yields a graph with about the right values for `C` and `L`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ws = nx.watts_strogatz_graph(n, k, 0.05, seed=15)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The clustering coefficient is a little higher than in the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "C, average_clustering(ws)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the path length is a little lower."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L, estimate_path_length(ws)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So that seems good so far."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Degree"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But let's look at the degree distribution.\n",
    "\n",
    "The following function returns a list of degrees, one for each node:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def degrees(G):\n",
    "    \"\"\"List of degrees for nodes in `G`.\n",
    "    \n",
    "    G: Graph object\n",
    "    \n",
    "    returns: list of int\n",
    "    \"\"\"\n",
    "    return [G.degree(u) for u in G]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The average degree in the WS model is about right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.mean(degrees(fb)), np.mean(degrees(ws))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But the standard deviation isn't even close:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.std(degrees(fb)), np.std(degrees(ws))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see what's going on, we need to look at the whole distribution.\n",
    "\n",
    "I'll start with a very small graph:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G = nx.Graph()\n",
    "G.add_edge(1, 0)\n",
    "G.add_edge(2, 0)\n",
    "G.add_edge(3, 0)\n",
    "nx.draw(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's what the list of degrees looks like for this graph:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "degrees(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To compute the degree distribution, I'll use the `Pmf` class from `thinkstats2`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from thinkstats2 import Pmf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `Pmf` object maps from each degree to the fraction of nodes with that degree."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Pmf(degrees(G))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "75% of the nodes have degree 1; 25% have degree 3.\n",
    "\n",
    "We can visualize the distribution as a histogram:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.Hist(Pmf(degrees(G)), width=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we can use the `Pmf` to compute mean and standard deviation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pmf_fb = Pmf(degrees(fb))\n",
    "pmf_fb.Mean(), pmf_fb.Std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pmf_ws = Pmf(degrees(ws))\n",
    "pmf_ws.Mean(), pmf_ws.Std()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also use the `Pmf` to look up the fraction of nodes with exactly 1 neighbor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pmf_fb[1], pmf_ws[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's what the degree distributions look like for the Facebook data and the WS model.  They don't resemble each other at all."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.preplot(cols=2)\n",
    "\n",
    "thinkplot.Pdf(pmf_fb, label='Facebook')\n",
    "thinkplot.config(xlabel='degree', ylabel='PMF')\n",
    "\n",
    "thinkplot.subplot(2)\n",
    "\n",
    "thinkplot.Pdf(pmf_ws, label='WS graph')\n",
    "thinkplot.config(xlabel='degree', ylabel='PMF')\n",
    "\n",
    "plt.savefig('chap04-1.pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can get a better view of the Facebook data by plotting the PMF on a log-log scale.\n",
    "\n",
    "The result suggests that the degree distribution follows a power law, at least for values larger than 10 or so.\n",
    "\n",
    "The log-log scale doesn't help the WS graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.preplot(cols=2)\n",
    "\n",
    "thinkplot.plot([20, 1000], [5e-2, 2e-4], color='gray', linestyle='dashed')\n",
    "\n",
    "thinkplot.Pdf(pmf_fb, style='.', label='Facebook')\n",
    "thinkplot.config(xscale='log', yscale='log',\n",
    "                 xlabel='degree', ylabel='PMF')\n",
    "\n",
    "thinkplot.subplot(2)\n",
    "\n",
    "thinkplot.Pdf(pmf_ws, style='.', label='WS graph')\n",
    "thinkplot.config(xlim=[35, 55], \n",
    "                 xscale='log', yscale='log',\n",
    "                 xlabel='degree', ylabel='PMF')\n",
    "\n",
    "plt.savefig('chap04-2.pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The discrepancy between the actual degree distribution and the WS model is the motivation for the BA model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BA model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's a simplified version of the NetworkX function that generates BA graphs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# modified version of the NetworkX implementation from\n",
    "# https://github.com/networkx/networkx/blob/master/networkx/generators/random_graphs.py\n",
    "\n",
    "def barabasi_albert_graph(n, k, seed=None):\n",
    "    \"\"\"Constructs a BA graph.\n",
    "    \n",
    "    n: number of nodes\n",
    "    k: number of edges for each new node\n",
    "    seed: random seen\n",
    "    \"\"\"\n",
    "    if seed is not None:\n",
    "        random.seed(seed)\n",
    "    \n",
    "    G = nx.empty_graph(k)\n",
    "    targets = set(range(k))\n",
    "    repeated_nodes = []\n",
    "\n",
    "    for source in range(k, n):\n",
    "\n",
    "        G.add_edges_from(zip([source]*k, targets))\n",
    "\n",
    "        repeated_nodes.extend(targets)\n",
    "        repeated_nodes.extend([source] * k)\n",
    "\n",
    "        targets = _random_subset(repeated_nodes, k)\n",
    "\n",
    "    return G"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here's the function that generates a random subset without repetition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def _random_subset(repeated_nodes, k):\n",
    "    \"\"\"Select a random subset of nodes without repeating.\n",
    "    \n",
    "    repeated_nodes: list of nodes\n",
    "    k: size of set\n",
    "    \n",
    "    returns: set of nodes\n",
    "    \"\"\"\n",
    "    targets = set()\n",
    "    while len(targets) < k:\n",
    "        x = random.choice(repeated_nodes)\n",
    "        targets.add(x)\n",
    "    return targets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I'll generate a BA graph with the same number of nodes and edges as the Facebook data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = len(fb)\n",
    "m = len(fb.edges())\n",
    "k = int(round(m/n))\n",
    "n, m, k"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Providing a random seed means we'll get the same graph every time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ba = barabasi_albert_graph(n, k, seed=15)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The number of edges is pretty close to what we asked for."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "len(ba), len(ba.edges()), len(ba.edges())/len(ba)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So the mean degree is about right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.mean(degrees(fb)), np.mean(degrees(ba))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The standard deviation of degree is pretty close, and much better than the WS model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.std(degrees(fb)), np.std(degrees(ba))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take a look at the degree distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pmf_ba = Pmf(degrees(ba))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looking at the PMFs on a linear scale, we see one difference, which is that the BA model has no nodes with degree less than `k`, which is 22."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.preplot(cols=2)\n",
    "\n",
    "thinkplot.Pdf(pmf_fb, label='Facebook')\n",
    "thinkplot.config(xlabel='degree', ylabel='PMF')\n",
    "\n",
    "thinkplot.subplot(2)\n",
    "\n",
    "thinkplot.Pdf(pmf_ba, label='BA graph')\n",
    "thinkplot.config(xlabel='degree', ylabel='PMF')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But if we look at the PMF on a log-log scale, the BA model looks pretty good for values bigger than about 20.  And it seems to follow a power law."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.preplot(cols=2)\n",
    "\n",
    "thinkplot.Pdf(pmf_fb, style='.', label='Facebook')\n",
    "thinkplot.config(xlabel='degree', ylabel='PMF')\n",
    "thinkplot.config(xscale='log', yscale='log')\n",
    "\n",
    "thinkplot.subplot(2)\n",
    "\n",
    "thinkplot.Pdf(pmf_ba, style='.', label='BA model')\n",
    "thinkplot.config(xlabel='degree', ylabel='PMF')\n",
    "thinkplot.config(xlim=[1, 1e4],\n",
    "                 xscale='log', yscale='log')\n",
    "\n",
    "plt.savefig('chap04-3.pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The characteristic path length is even smaller in the model than in the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L, estimate_path_length(ba)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But the clustering coefficient isn't even close."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "C, average_clustering(ba)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the BA model, the degree distribution is better than in the WS model, but the clustering coefficient is too low."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cumulative distributions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Cumulative distributions are a better way to visualize distributions.  The following function shows what a cumulative probability is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cumulative_prob(pmf, x):\n",
    "    \"\"\"Computes the cumulative probability of `x`.\n",
    "    \n",
    "    Total probability of all values <= x.\n",
    "    \n",
    "    returns: float probability\n",
    "    \"\"\"\n",
    "    ps = [pmf[value] for value in pmf if value<=x]\n",
    "    return sum(ps)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The total probability for all values up to and including 11 is 0.258, so the 25th percentile is about 11."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cumulative_prob(pmf_fb, 11)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The median degree is about 25."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cumulative_prob(pmf_fb, 25)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the 75th percentile is about 57.  That is, about 75% of users have 57 friends or fewer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cumulative_prob(pmf_fb, 57)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`thinkstats2` provides `Cdf`, which computes cumulative distribution functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from thinkstats2 import Cdf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here are the degree CDFs for the Facebook data, the WS model, and the BA model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cdf_fb = Cdf(degrees(fb), label='Facebook')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cdf_ws = Cdf(degrees(ws), label='WS model')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cdf_ba = Cdf(degrees(ba), label='BA model')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we plot them on a log-x scale, we get a sense of how well the models fit the central part of the distribution.\n",
    "\n",
    "The WS model is hopeless.  The BA model is ok for values above the median, but not very good for smaller values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.preplot(cols=2)\n",
    "\n",
    "thinkplot.Cdf(cdf_fb)\n",
    "thinkplot.Cdf(cdf_ws, color='gray')\n",
    "thinkplot.config(xlabel='degree', xscale='log',\n",
    "                 ylabel='CDF')\n",
    "\n",
    "thinkplot.subplot(2)\n",
    "\n",
    "thinkplot.Cdf(cdf_fb, label='Facebook')\n",
    "thinkplot.Cdf(cdf_ba, color='gray')\n",
    "thinkplot.config(xlabel='degree', xscale='log',\n",
    "                 ylabel='CDF')\n",
    "\n",
    "plt.savefig('chap04-4.pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On a log-log scale, we see that the BA model fits the tail of the distribution reasonably well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "thinkplot.preplot(cols=2)\n",
    "\n",
    "thinkplot.Cdf(cdf_fb, complement=True)\n",
    "thinkplot.Cdf(cdf_ws, color='gray', complement=True)\n",
    "thinkplot.config(xlabel='degree', xscale='log',\n",
    "                 ylabel='CCDF', yscale='log')\n",
    "\n",
    "thinkplot.subplot(2)\n",
    "\n",
    "thinkplot.Cdf(cdf_fb, label='Facebook', complement=True)\n",
    "thinkplot.Cdf(cdf_ba, color='gray', complement=True)\n",
    "thinkplot.config(xlabel='degree', xscale='log',\n",
    "                 ylabel='CCDF', yscale='log')\n",
    "\n",
    "plt.savefig('chap04-5.pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But there is certainly room for a model that does a better job of fitting the whole distribution."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Data files from the Barabasi and Albert paper are available from\n",
    "[this web page](http://www3.nd.edu/~networks/resources.htm).\n",
    "\n",
    "Their actor collaboration data is included in the repository for this book in a file named\n",
    "`actor.dat.gz`.  The following function reads the file and builds the graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gzip\n",
    "\n",
    "def read_actor_network(filename, n=None):\n",
    "    \"\"\"Reads graph data from a file.\n",
    "    \n",
    "    filename: string\n",
    "    n: int, number of lines to read (default is all)\n",
    "    \"\"\"\n",
    "    G = nx.Graph()\n",
    "    with gzip.open(filename) as f:\n",
    "        for i, line in enumerate(f):\n",
    "            nodes = [int(x) for x in line.split()]\n",
    "            G.add_edges_from(all_pairs(nodes))\n",
    "            if n and i >= n:\n",
    "                break\n",
    "    return G\n",
    "\n",
    "def all_pairs(nodes):\n",
    "    \"\"\"Generates all pairs of nodes.\"\"\"\n",
    "    for i, u in enumerate(nodes):\n",
    "        for j, v in enumerate(nodes):\n",
    "            if i < j:\n",
    "                yield u, v"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compute the number of actors in the graph and the number of edges.\n",
    "\n",
    "Check whether this graph has the small world properties, high clustering and low\n",
    "path length.\n",
    "\n",
    "Plot the PMF of degree on a log-log scale.  Does it seem to follow a power law?\n",
    "\n",
    "Also plot the CDF of degree on a log-x scale, to \n",
    "see the general shape of the distribution, and on a log-log scale, to see whether \n",
    "the tail follows a power law.\n",
    "\n",
    "Note: The actor network is not connected, so you might want to use\n",
    "`nx.connected_components` to find connected subsets of the\n",
    "nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# WARNING: if you run this with larger values of `n`, you\n",
    "# might run out of memory, and Jupyter does not handle that well.\n",
    "\n",
    "%time actors = read_actor_network('actor.dat.gz', n=10000)\n",
    "len(actors)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** NetworkX provides a function called `powerlaw_cluster_graph` that implements the \"Holme and Kim algorithm for growing graphs with powerlaw degree distribution and approximate average clustering\".  Read the documentation of this function and see if you can use it to generate a graph that has the same number of nodes as the Facebook network, the same average degree, and the same clustering coefficient.  How does the degree distribution in the model compare to the actual distribution?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
